package cn.xiaye.httpserver;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

/**
 * 响应客户请求类
 * 
 * @author 王夏夜
 * 
 */
public class Response {
	/**
	 * 输出流
	 */
	PrintWriter out = null;
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	OutputStream socketOut = null;

	public Response(Socket sock) throws IOException {
		out = new PrintWriter(bos);
		socketOut = sock.getOutputStream();
	}

	public PrintWriter getOut() {
		return out;
	}

	public void setOut(PrintWriter out) {
		this.out = out;
	}

	public void flushResponse() throws IOException {
		out.flush();
		out.close();
		byte[] buffer = bos.toByteArray();
		bos.close();
		String header = this.toHeadString(buffer.length);
		socketOut.write(header.getBytes());
		socketOut.write(buffer);
		socketOut.flush();
	}

	/**
	 * 生成响应头信息
	 * 
	 * @param len
	 * @return
	 */
	public String toHeadString(int len) {
		StringBuffer sb = new StringBuffer();
		sb.append("HTTP/1.1 200 OK\r\n");
		sb.append("Date: " + new Date() + "\r\n");
		sb.append("Server: BWS/1.0\r\n");
		sb.append("Content-Length: " + len + "\r\n");
		sb.append("Content-Type: text/html;charset=utf-8\r\n");
		sb.append("Cache-Control: private\r\n");
		// sb.append("Content-Encoding: gzip\r\n");
		sb.append("Connection: Keep-Alive\r\n");
		sb.append("\r\n");
		return sb.toString();
	}

	/**
	 * 将file内容返还给客户端
	 * 
	 * @param filepath
	 * @throws IOException
	 */
	public void responseFile(String filepath) {
		if (filepath == null) {
			return;
		}
		File file = new File(Constant.WEBROOT_PATH + File.separator + filepath);
		FileReader fr = null;
		try {
			fr = new FileReader(file);
			int c = -1;
			while ((c = fr.read()) != -1) {
				out.write(c);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace(out);
		} catch (IOException e) {
			e.printStackTrace(out);
		} finally {
			if (fr != null) {
				try {
					fr.close();
				} catch (IOException e) {
					e.printStackTrace(out);
				}
			}
		}
	}
}
